<?php
/*
Copyright (c) 2009~2020, whentp
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the whentp nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY whentp ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL whentp BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

require_once 'config.php';
//require_once 'user.php';


function user_oauth() {
	require_once 'OAuth.php';
	session_start();
	setCookie('Oauth', 'oauth', time()+3600*24*1000);

	if ($oauth_token = $_GET['oauth_token']) {
		$params = array('oauth_verifier' => $_GET['oauth_verifier']);
		$response = oauth_process('https://twitter.com/oauth/access_token', $params);
		parse_str($response, $token);
		setCookie('up', $token['oauth_token'].'|'.$token['oauth_token_secret'],time()+3600*24*1000);
		unset($_SESSION['oauth_request_token_secret']);
		setCookie('l', 'OK', time()+3600*24*1000);
		header('Location: '. BASE_URL);
		exit();

	} else {
		$params = array('oauth_callback' => BASE_URL);
		$response = oauth_process('https://twitter.com/oauth/request_token', $params);
		parse_str($response, $token);
		$_SESSION['oauth_request_token_secret'] = $token['oauth_token_secret'];
		$authorise_url = 'https://twitter.com/oauth/authorize?oauth_token='.$token['oauth_token'];
		header("Location: $authorise_url");
	}
}

function user_oauth_sign(&$url, &$args = false) {
	require_once 'OAuth.php';
	$method = $args !== false ? 'POST' : 'GET';

	if (preg_match_all('#[?&]([^=]+)=([^&]+)#', $url, $matches, PREG_SET_ORDER)) {
		foreach ($matches as $match){$args[$match[1]] = $match[2];}
			$url = substr($url, 0, strpos($url, '?'));
	}

	$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
	$consumer = new OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
	$token = NULL;

	if (($oauth_token = $_GET['oauth_token']) && $_SESSION['oauth_request_token_secret']) {
		$oauth_token_secret = $_SESSION['oauth_request_token_secret'];
	} else {
		list($oauth_token, $oauth_token_secret) = explode('|', $_COOKIE['up']);
	}

	if ($oauth_token && $oauth_token_secret) {
		$token = new OAuthConsumer($oauth_token, $oauth_token_secret);
	}

	$request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $url, $args);
	$request->sign_request($sig_method, $consumer, $token);

	switch ($method) {
	case 'GET':
		$url = $request->to_url();
		$args = false;
		return;
	case 'POST':
		$url = $request->get_normalized_http_url();
		$args = $request->to_postdata();
		return;
	}
}

function oauth_process($url, $post_data = false) {
	if ($post_data === true) $post_data = array();
	user_oauth_sign($url, $post_data);
	
	$ch = curl_init($url);
	if($post_data !== false) {
		curl_setopt ($ch, CURLOPT_POST, true);
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
	}
	
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_USERAGENT, 'kwestion');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$response = curl_exec($ch);
	$response_info=curl_getinfo($ch);
	curl_close($ch);
	if(intval($response_info['http_code']) == 200) {
		$json = json_decode($response);
		if ($json) return $json;
		return $response;
	}else{
		setCookie('Oauth', 'oauth', time()-3600*24*1000);
		header('Location: '. BASE_URL);
	}
}

function user_type(){
	return isset($_COOKIE["Oauth"]) && $_COOKIE['Oauth'] == 'oauth';
}

function twitter_process($url, $post_data = false) {
	return raw_twitter_process(getU(),getP(),$url,$post_data);
}

function raw_twitter_process($u,$p,$url,$post_data = false){
	if ($post_data === true) $post_data = array();
	//Some POSTable twitter methods are on http://api.twitter.com not http://twitter.com
	if (user_type() && ( strpos($url, '/twitter.com') !== false || strpos($url, 'api.twitter.com') !== false) ) {
		user_oauth_sign($url, $post_data);
	} elseif (strpos($url, 'twitter.com') !== false && is_array($post_data)) {
		// Passing $post_data as an array to twitter.com (non-oauth) causes an error :(
		$s = array();
		foreach ($post_data as $name => $value)
			$s[] = $name.'='.urlencode($value);
		$post_data = implode('&', $s);
	}

	$ch = curl_init($url);

	if($post_data !== false && strpos($post_data,'page')===false) {
		curl_setopt ($ch, CURLOPT_POST, true);
		//echo $post_data;
		curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
	}

	if (!user_type())
		curl_setopt($ch, CURLOPT_USERPWD, $u.':'.$p);


	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_VERBOSE, 0);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_USERAGENT, 'kwestion');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	$response = curl_exec($ch);
	$response_info=curl_getinfo($ch);
	curl_close($ch);

	//echo $response;
	if(intval( $response_info['http_code'])==200){

		$json = json_decode($response);
		if(!($json===false)){
			return $json;
		}
		else{
			return false;
		}
	}
	else{
		return false;
	}
}

function preg_match_one($pattern, $subject, $flags = NULL) {
	preg_match($pattern, $subject, $matches, $flags);
	return trim($matches[1]);
}

function parse_thread($html){
	$output = array();
	$html_tweets = explode('</li>', $html);
	foreach ($html_tweets as $tweet) {
		$id = preg_match_one('#msgtxt(\d*)#', $tweet);
		if (!$id) continue;
		$output[] = (object) array(
			'id' => $id,
			'text' => strip_tags(preg_match_one('#</a>: (.*)</span>#', $tweet)),
			'source' => preg_match_one('#>from (.*)</span>#', $tweet),
			'from' => (object) array(
				'id' => preg_match_one('#profile_images/(\d*)#', $tweet),
				'screen_name' => preg_match_one('#twitter.com/([^"]+)#', $tweet),
				'profile_image_url' => preg_match_one('#src="([^"]*)"#' , $tweet),
			),
			'to' => (object) array(
				'screen_name' => preg_match_one('#@([^<]+)#', $tweet),
			),
			'created_at' => str_replace('about', '', preg_match_one('#info">\s(.*)#', $tweet)),
		);
	}
	return $output;
}


function processstatuses($statuses){
	$newstatuses = array();
	//var_dump($statuses);
	if(!is_array($statuses))
		return array();
	foreach($statuses as $t){
		$newstatuses[] = processstatus($t);
	}
	return $newstatuses;
}

function processstatus($status){
	$text = $status->text;
	//$text = unshorturl($status->text);
	$text = twitter_parse_tags($text);
	$status->processedtext = $text; 
	return $status;
}

function twitter_parse_tags($input){
	$out = preg_replace('#(\w+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)(?<![.,])#', '<a href="$1" target="_blank">$1</a>', $input);
	$out = twitter_photo_replace($out);
	return $out;
}

function twitter_photo_replace($text) {
	$images = array();
	$tmp = strip_tags($text);

	$services = array(
		'#youtube\.com\/watch\?v=([_-\d\w]+)#i' => 'http://i.ytimg.com/vi/%s/1.jpg',
		'#youtu\.be\/([_-\d\w]+)#i' => 'http://i.ytimg.com/vi/%s/1.jpg',
		'#twitpic.com/([\d\w]+)#i' => 'http://twitpic.com/show/thumb/%s',
		'#twitgoo.com/([\d\w]+)#i' => 'http://twitgoo.com/show/thumb/%s',
		'#yfrog.com/([\w\d]+)#i' => 'http://yfrog.com/%s.th.jpg',
		'#moblog.net/view/([\d]+)/#' => 'moblog/%s',
		'#hellotxt.com/i/([\d\w]+)#i' => 'http://hellotxt.com/image/%s.s.jpg',
		'#ts1.in/(\d+)#i' => 'http://ts1.in/mini/%s',
		'#moby.to/\??([\w\d]+)#i' => 'http://moby.to/%s:square',
		'#mobypicture.com/\?([\w\d]+)#i' => 'http://mobypicture.com/?%s:square',
		'#twic.li/([\w\d]{2,7})#' => 'http://twic.li/api/photo.jpg?id=%s&size=small',
		'#tweetphoto.com/(\d+)#' => 'http://TweetPhotoAPI.com/api/TPAPI.svc/json/imagefromurl?size=thumbnail&url=http://tweetphoto.com/%s',
	);

	// Loop through each service and show images for matching URLs
	foreach ($services as $pattern => $thumbnail_url) {
		if (preg_match_all($pattern, $tmp, $matches, PREG_PATTERN_ORDER) > 0) {
			foreach ($matches[1] as $key => $match) {
				$images[] = '<a href="http://'.$matches[0][$key].'" target="_blank"><img src="'.sprintf($thumbnail_url, $match).'" /></a>';
			}
		}
	}

	// Twitxr is handled differently because of their folder structure
	if (preg_match_all('#twitxr.com/[^ ]+/updates/([\d]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0) {
		foreach ($matches[1] as $key => $match) {
			$thumb = 'http://twitxr.com/thumbnails/'.substr($match, -2).'/'.$match.'_th.jpg';
			$images[] = '<a href="http://'.$matches[0][$key].'" target="_blank">"<img src="'.$thumb.'" /></a>';
		}
	}

	// AudioBoo is handled differently because we link directly to an MP3, not an image
	if (preg_match_all('#boo.fm/b([\d]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0) {
		foreach ($matches[1] as $key => $match) {
			$images[] = "<a href='http://{$matches[0][$key]}.mp3' target='_blank'>[点击此处听音乐]</a>";
		}
	}

	// match phz.in (short phreadz)  urls
	if (preg_match_all('#phz.in/([\d\w]+)#', $tmp, $matches, PREG_PATTERN_ORDER) > 0){
		foreach ($matches[1] as $match){
			//Images from Phreadz aren't always suitable for mobile, so we use http://tinysrc.mobi/ to convert them
			$thumb = "http://i.tinysrc.mobi/x50/http://api.phreadz.com/thumb/" . $match . "?t=code";
			$images[] = '<a href="http://phz.in/'. $match.'" target="_blank"><img src="'.$thumb.'" /></a>';
		}
	}  

	if (empty($images)) return $text;
	return implode('<br />', $images).'<br />'.$text;
}

function unshorturl($text){
	$urlregs = array();
	$urlregs[] ='/tinyurl\.com\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/bit\.ly\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/twurl\.nl\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/j\.mp\/([a-z0-9]{5}[a-z0-9]*)/i';
	//$urlregs[] ='/is\.gd\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/retwt\.me\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/ff\.im\/-([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/tr\.im\/([a-z0-9]{5}[a-z0-9]*)/i';
	$urlregs[] ='/htxt\.it\/([a-z0-9]{4}[a-z0-9]*)/i';
	$urlregs[] ='/aa\.cx\/([a-z0-9]*)/i';
	$urlregs[] ='/2\.ly\/([a-z0-9]*)/i';
	//$text .='!!!';
	foreach($urlregs as $urlreg) {
		if(preg_match($urlreg,$text,$match)){
			$request = 'http://api.unshort.me/?r='.urlencode('http://' . $match[0]);
			$tmpstr = processcurl($request);
			$url = substr($tmpstr,13+strpos($tmpstr,"<resolvedURL>"),strpos($tmpstr,"</resolvedURL>") - 13 - strpos($tmpstr,"<resolvedURL>"));
			$text = str_replace('http://'.$match[0], $url, $text);
		}
	}
	return $text;
}

function utf8_substr($str,$start){ 
	preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $str, $ar);
	var_dump($ar);
	if(func_num_args() >= 3) { 
		$end = func_get_arg(2); 
		return join("",array_slice($ar[0],$start,$end)); 
	} else { 
		return join("",array_slice($ar[0],$start)); 
	}

}

function utf8_strlen($str){
	preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $str, $ar);
		var_dump($ar);

	return count($ar[0]);
}

function processcurl($url,$postargs=false){
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$response = curl_exec($ch);
	$responseInfo=curl_getinfo($ch);
	curl_close($ch);
	if( intval( $responseInfo['http_code'] ) == 200 )
		return $response;    
	else
		return false;
}

function getU(){
	if(isset($_COOKIE['un']))
		return trim($_COOKIE['un']);
	return '';
}

function getP(){
	if(isset($_COOKIE['up']))
		return trim($_COOKIE['up']);
	return '';
}

function isLogin(){
	if(isset($_COOKIE['l'])){
		return $_COOKIE['l'] == 'OK';
	}
	return false;
}

function compress($content){ 
	if( !headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){
		$content = gzencode($content." \n",1);
		header("Content-Encoding: gzip"); 
		header("Vary: Accept-Encoding");
		header("Content-Length: ".strlen($content));
	}
	return $content;
}

?>
